#nullable enable
using System.Linq;
using Godot;
using AndroidUnevenRoadGame.Game;

namespace AndroidUnevenRoadGame.UI
{
    public partial class HanfuScene : Control
    {
        [Export] private Label? _infoLabel;
        [Export] private Button? _restButton;
        [Export] private Button? _removeButton;
        [Export] private Button? _upgradeButton;
        [Export] private Button? _leaveButton;
        [Export] private ItemList? _deckList;
        [Export] private Label? _messageLabel;
        private bool _hasRested;
        private int _removeRemaining = 2;
        private int _upgradeRemaining = 2;
        private readonly System.Collections.Generic.List<string> _deckEntries = new();

        public override void _Ready()
        {
            _infoLabel ??= GetNode<Label>("Panel/VBox/InfoLabel");
            _restButton ??= GetNode<Button>("Panel/VBox/ButtonRow/RestButton");
            _removeButton ??= GetNode<Button>("Panel/VBox/ButtonRow/RemoveButton");
            _upgradeButton ??= GetNode<Button>("Panel/VBox/ButtonRow/UpgradeButton");
            _leaveButton ??= GetNode<Button>("Panel/VBox/ButtonRow/LeaveButton");
            _deckList ??= GetNode<ItemList>("Panel/VBox/DeckList");
            _messageLabel ??= GetNode<Label>("Panel/VBox/MessageLabel");

            _restButton!.Pressed += OnRestPressed;
            _removeButton!.Pressed += OnRemovePressed;
            _upgradeButton!.Pressed += OnUpgradePressed;
            _leaveButton!.Pressed += OnLeavePressed;

            UpdateInfo();
            PopulateDeck();
            UpdateMessage("请选择操作：休息、移除或升级卡牌。");
            UpdateActionButtons();
        }

        private void UpdateInfo()
        {
            var player = GameRoot.Instance.Player;
            _infoLabel!.Text = $"当前生命：{player.CurrentHp}/{player.MaxHp}";
        }

        private void OnRestPressed()
        {
            if (_hasRested)
            {
                UpdateMessage("已进行过休息。");
                return;
            }

            var game = GameRoot.Instance;
            var targetHp = Mathf.CeilToInt(game.Player.MaxHp * (2f / 3f));
            var healAmount = Mathf.Max(0, targetHp - game.Player.CurrentHp);
            if (healAmount > 0)
            {
                game.Player.Heal(healAmount);
                UpdateMessage($"休整恢复 {healAmount} 点生命。");
            }
            else
            {
                UpdateMessage("生命值已超过 2/3，无需休息。");
            }

            _hasRested = true;
            _restButton!.Disabled = true;
            _restButton.Text = healAmount > 0 ? $"已休整 (+{healAmount})" : "已休整";
            UpdateInfo();
            UpdateActionButtons();
        }

        private void OnRemovePressed()
        {
            if (_deckList == null)
            {
                return;
            }

            if (_removeRemaining <= 0)
            {
                UpdateMessage("本次最多移除 2 张卡牌，机会已用完。");
                return;
            }

            var selected = _deckList.GetSelectedItems();
            if (selected.Length == 0)
            {
                UpdateMessage($"请从列表中选择要移除的卡牌（剩余可移除 {_removeRemaining} 张）。");
                return;
            }

            if (selected.Length > _removeRemaining)
            {
                UpdateMessage($"一次最多还可移除 {_removeRemaining} 张卡牌，请减少选择数量。");
                return;
            }

            var player = GameRoot.Instance.Player;
            var removedCount = 0;
            foreach (var indexLong in selected)
            {
                var index = (int)indexLong;
                if (index < 0 || index >= _deckEntries.Count)
                {
                    continue;
                }
                var cardId = _deckEntries[index];
                if (player.RemoveCard(cardId))
                {
                    removedCount++;
                }
            }

            if (removedCount == 0)
            {
                UpdateMessage("没有移除任何卡牌，可能所选卡牌已不存在。");
                return;
            }

            _removeRemaining -= removedCount;
            if (_removeRemaining <= 0)
            {
                _removeRemaining = 0;
            }

            UpdateMessage($"已移除 {removedCount} 张卡牌，剩余可移除 {_removeRemaining} 张。");
            PopulateDeck();
            UpdateActionButtons();
        }

        private void OnUpgradePressed()
        {
            if (_deckList == null)
            {
                return;
            }

            if (_upgradeRemaining <= 0)
            {
                UpdateMessage("本次最多升级 2 张卡牌，机会已用完。");
                return;
            }

            var selected = _deckList.GetSelectedItems();
            if (selected.Length == 0)
            {
                UpdateMessage($"请从列表中选择要升级的卡牌（剩余可升级 {_upgradeRemaining} 张）。");
                return;
            }

            if (selected.Length > _upgradeRemaining)
            {
                UpdateMessage($"一次最多还可升级 {_upgradeRemaining} 张卡牌，请减少选择数量。");
                return;
            }

            var player = GameRoot.Instance.Player;
            var upgradedCount = 0;
            var nonUpgradable = new System.Collections.Generic.List<string>();

            foreach (var indexLong in selected)
            {
                var index = (int)indexLong;
                if (index < 0 || index >= _deckEntries.Count)
                {
                    continue;
                }

                var cardId = _deckEntries[index];
                if (!CardDatabase.HasUpgrade(cardId))
                {
                    nonUpgradable.Add(CardDatabase.Get(cardId).Name);
                    continue;
                }

                if (player.UpgradeCard(cardId))
                {
                    upgradedCount++;
                }
            }

            if (upgradedCount == 0)
            {
                if (nonUpgradable.Count > 0)
                {
                    UpdateMessage($"所选卡牌不可升级：{string.Join("、", nonUpgradable)}。");
                }
                else
                {
                    UpdateMessage("未能升级任何卡牌，可能已全部升级。");
                }
                return;
            }

            _upgradeRemaining -= upgradedCount;
            if (_upgradeRemaining <= 0)
            {
                _upgradeRemaining = 0;
            }

            if (nonUpgradable.Count > 0)
            {
                UpdateMessage($"成功升级 {upgradedCount} 张卡牌，剩余可升级 {_upgradeRemaining} 张。以下卡牌不可升级：{string.Join("、", nonUpgradable)}。");
            }
            else
            {
                UpdateMessage($"成功升级 {upgradedCount} 张卡牌，剩余可升级 {_upgradeRemaining} 张。");
            }

            PopulateDeck();
            UpdateActionButtons();
        }

        private void OnLeavePressed()
        {
            var game = GameRoot.Instance;
            game.AdvanceFloor();
            game.ChangeState(GameRoot.GameState.Map);
        }

        private void PopulateDeck()
        {
            if (_deckList == null)
            {
                return;
            }

            _deckEntries.Clear();
            _deckList.Clear();

            var player = GameRoot.Instance.Player;
            var counts = new System.Collections.Generic.Dictionary<string, int>();
            foreach (var cardId in player.EnumerateAllCards())
            {
                if (!counts.TryAdd(cardId, 1))
                {
                    counts[cardId]++;
                }
            }

            if (counts.Count == 0)
            {
                UpdateMessage("当前牌组为空，无可管理的卡牌。");
                return;
            }

            foreach (var kvp in counts.OrderBy(k => CardDatabase.Get(k.Key).Name))
            {
                var card = CardDatabase.Get(kvp.Key);
                var status = CardDatabase.HasUpgrade(kvp.Key)
                    ? " [可升级]"
                    : (card.Id.Contains("_plus") ? " [已升级]" : string.Empty);
                var display = $"{card.Name} ×{kvp.Value} ({card.Id}){status}";
                _deckEntries.Add(kvp.Key);
                _deckList.AddItem(display);
                var itemIndex = _deckList.ItemCount - 1;
                _deckList.SetItemTooltip(itemIndex, card.Description);
            }
        }

        private void UpdateMessage(string text)
        {
            if (_messageLabel != null)
            {
                _messageLabel.Text = text;
            }
        }

        private void UpdateActionButtons()
        {
            if (_removeButton != null)
            {
                _removeButton.Disabled = _removeRemaining <= 0;
                _removeButton.Text = _removeRemaining <= 0 ? "移除卡牌（已完成）" : $"移除卡牌（剩余 {_removeRemaining} 张）";
            }

            if (_upgradeButton != null)
            {
                _upgradeButton.Disabled = _upgradeRemaining <= 0;
                _upgradeButton.Text = _upgradeRemaining <= 0 ? "升级卡牌（已完成）" : $"升级卡牌（剩余 {_upgradeRemaining} 张）";
            }

            if (_restButton != null)
            {
                if (!_hasRested)
                {
                    _restButton.Disabled = false;
                    _restButton.Text = "休整回复生命";
                }
            }
        }
    }
}

